<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="款项类型" prop="moneyType">
        <el-select
          v-model="queryParams.moneyType"
          placeholder="请选择款项类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.crm_money_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="款项归属人" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择款项类型"
          style="width: 100%"
          clearable
          filterable
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属商机" prop="orderId">
        <el-select
          v-model="queryParams.orderId"
          placeholder="请选择项目"
          style="width: 100%"
          clearable
          filterable
        >
          <el-option
            v-for="project in projectList"
            :key="project.orderId"
            :label="project.orderName"
            :value="project.orderId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:collectPayMoney:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:collectPayMoney:edit']"
          >修改</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:collectPayMoney:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:collectPayMoney:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="collectPayMoneyList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属商机" align="center" prop="orderName" />
      <el-table-column label="所属客户" align="center" prop="customerName" />
      <el-table-column label="款项归属人" align="center" prop="userName" />
      <el-table-column label="款项类型" align="center" prop="moneyType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.crm_money_type"
            :value="scope.row.moneyType"
          />
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_audit_status"
            :value="scope.row.auditStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="120"
      >
        <template slot-scope="scope">
            <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="submit(scope.row)"
            v-show="scope.row.auditStatus === '0'"
            >提交</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="cancelInfo(scope.row)"
            v-show="scope.row.auditStatus === '1'"
            >撤回</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:collectPayMoney:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:collectPayMoney:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收付款管理对话框 -->
    <el-drawer
      ref="drawer"
      :title="title"
      direction="rtl"
      :visible.sync="open"
      size="80%"
      append-to-body
      :wrapperClosable="false"
    >
      <el-card
        class="box-card"
        style="width: 96%; margin-left: 20px; min-height: 90vh"
      >
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-col :span="8">
              <el-form-item label="款项类型" prop="moneyType">
                <el-select
                  v-model="form.moneyType"
                  placeholder="请选择款项类型"
                  style="width: 100%"
                  :disabled="form.collectPayMoneyId !== null && form.collectPayMoneyId !== ''"
                >
                  <el-option
                    v-for="dict in dict.type.crm_money_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属项目" prop="orderId">
                <el-select
                  v-model="form.orderId"
                  @change="getOrderRegisterInfo"
                  placeholder="请选择项目"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.orderId"
                    :label="project.orderName"
                    :value="project.orderId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="款项归属人" prop="userId">
                <el-select
                  v-model="form.userId"
                  placeholder="请选择款项类型"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.userId"
                    :label="user.userName"
                    :value="user.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.moneyType === '1'">
              <el-form-item
                label="收款详情"
                prop="collectDetailsList"
                class="collectDetailsList"
              >
                <el-table :data="form.collectDetailsList" style="width: 100%">
                  <el-table-column
                    label="收款名称"
                    prop="collectDetailsName"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.collectDetailsName"
                        placeholder="请选择收款类型"
                      >
                        <el-option
                          v-for="dict in dict.type.crm_money_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预计收款时间"
                    prop="collectDetailsTime"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-date-picker
                        v-model="scope.row.collectDetailsTime"
                        style="width: 100%"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预计收款时间"
                      >
                      </el-date-picker>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预计收款金额(元)"
                    prop="collectDetailsAmount"
                    width="280"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.collectDetailsAmount"
                        placeholder="请输入预计收款金额"
                        type="number"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="收款状态"
                    prop="collectDetailsAmount"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.collectDetailsStatus"
                        placeholder="请选择收款状态"
                      >
                        <el-option
                          v-for="dict in dict.type.crm_collect_money_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="remark" width="330">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    width="100"
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                  >
                    <template slot-scope="scope">
                      <el-button
                        v-if="
                          scope.$index === form.collectDetailsList.length - 1
                        "
                        size="mini"
                        type="text"
                        icon="el-icon-plus"
                        @click="addExpenses(form.collectDetailsList, '0')"
                        >新增</el-button
                      >
                      <el-button
                        v-if="form.collectDetailsList.length > 1"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        style="color: red"
                        :disabled="scope.row.flag"
                        @click="
                          delExpenses(form.collectDetailsList, scope.$index)
                        "
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-else>
              <el-form-item
                label="付款详情"
                prop="payDetailsList"
                class="collectDetailsList"
              >
                <el-table :data="form.payDetailsList" style="width: 100%">
                  <el-table-column label="费用类型" prop="detailsName" width="200">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.detailsType"
                        placeholder="请选择费用类型"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="dict in dict.type.crm_fee_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="付款名称"
                    prop="detailsName"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.detailsName"
                        placeholder="请输入付款名称"
                        :readonly="scope.row.flag"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="付款时间"
                    prop="payDetailsTime"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-date-picker
                        v-model="scope.row.payDetailsTime"
                        style="width: 100%"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择付款时间"
                      >
                      </el-date-picker>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="付款金额(元)"
                    prop="detailsAmount"
                    width="280"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.detailsAmount"
                        placeholder="请输付款金额"
                        type="number"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="付款状态"
                    prop="payDetailsStatus"
                    fixed="right"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.payDetailsStatus"
                        placeholder="请选择付款状态"
                      >
                        <el-option
                          v-for="dict in dict.type.crm_pay_money_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="remark" width="330">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                    width="120"
                    fixed="right"
                    class-name="small-padding fixed-width"
                  >
                    <template slot-scope="scope">
                      <el-button
                        v-if="scope.$index === form.payDetailsList.length - 1"
                        size="mini"
                        type="text"
                        icon="el-icon-plus"
                        @click="addExpenses(form.payDetailsList, '1')"
                        >新增</el-button
                      >
                      <el-button
                        v-if="form.payDetailsList.length > 1"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        style="color: red"
                        :disabled="scope.row.flag"
                        @click="
                          delExpenses(form.payDetailsList, scope.$index)
                        "
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" @click="submitForm('1')">提 交</el-button>
                <el-button type="info" @click="submitForm('0')">暂 存</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import {
  listCollectPayMoney,
  getCollectPayMoney,
  delCollectPayMoney,
  addCollectPayMoney,
  updateCollectPayMoney,
  cancelInfo,
  submit
} from "@/api/crm/collectPayMoney";

import { getPayAmtList, getCollectionAmtList } from "@/api/crm/statistics";

import { getOrderRegisterInfo } from "@/api/crm/orderRegister";
export default {
  name: "CollectPayMoney",
  dicts: [
    "crm_money_type",
    "crm_money_status",
    "crm_collect_money_status",
    "crm_pay_money_status",
    "sys_audit_status",
    "crm_fee_type"
  ],
  props: {
    userList: {
      type: Array,
      default: [],
    },
    projectList: {
      type: Array,
      default: [],
    },
    query: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //付款金额明细
      detailsList: [],
      // 收付款管理表格数据
      collectPayMoneyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        moneyType: null,
        userId: null,
        orderId: null,
        projectId: null,
        auditStatus: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
      },
      // 表单参数
      form: {
        moneyType: "1",
        collectDetailsList: [
          {
            collectDetailsName: null,
            collectDetailsTime: new Date(),
            collectDetailsAmount: 0,
            collectDetailsStatus: "0",
            remark: "",
          },
        ],
        payDetailsList: [
          {
            detailsName: null,
            payDetailsTime: new Date(),
            detailsAmount: 0,
            payDetailsStatus: "0",
            remark: "",
          },
        ],
      },
  
      // 表单校验
      rules: {
        moneyType: [
          { required: true, message: "款项类型不能为空", trigger: "change" },
        ],
        userId: [
          { required: true, message: "款项归属人不能为空", trigger: "blur" },
        ],
        orderId: [
          { required: true, message: "商机id不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "项目id不能为空", trigger: "blur" },
        ],
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" },
        ],
        collectDetailsList: {
          required: true,
          validator: this.validateDetails,
          trigger: "change",
        },
        payDetailsList: {
          required: true,
          validator: this.validatePayDetails,
          trigger: "change",
        },
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    validateDetails(rule, value, callback) {
      const isValid = this.form.collectDetailsList.every((item) => {
        return (
          item.collectDetailsName &&
          item.collectDetailsTime &&
          (item.collectDetailsAmount || item.collectDetailsAmount === 0) &&
          item.collectDetailsStatus
        ); // 检查每一项必填
      });
      if (!isValid) {
        callback(
          new Error("收款名称、预计收款时间、预计收款金额、收款状态不能为空")
        );
      } else {
        callback();
      }
    },
    /** 表单悬着项目id 获取项目立项费用 */
    getOrderRegisterInfo(value) {
      getOrderRegisterInfo({ orderId: value }).then((res) => {
        this.form.payDetailsList = res.data.detailsList;
        this.form.payDetailsList = this.form.payDetailsList
        .filter(item => item.detailsAmount !== null && item.detailsAmount !== '')
        .map(item => ({
          ...item,
          flag: true
        }));
        console.log(this.form)
      });
    },
    validatePayDetails(rule, value, callback) {
      const isValid = this.form.payDetailsList.every((item) => {
        return (
          item.detailsName &&
          (item.detailsAmount || item.detailsAmount === 0) &&
          item.payDetailsStatus
        ); // 检查每一项必填
      });
      if (!isValid) {
        callback(new Error("付款名称、付款金额、付款状态不能为空"));
      } else {
        callback();
      }
    },
    addExpenses(detailList, flag) {
      let obj = {}

      if(flag === '0') {
          obj = {
              collectDetailsName: null,
              collectDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
              collectDetailsAmount: 0,
              collectDetailsStatus: "0",
              collectDetailsTimeFlag: false
          }
      } else {
          obj = {
              detailsName: null,
              payDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
              detailsAmount: 0,
              payDetailsStatus: "0",
              remark: "",
              payDetailsTimeFlag: false
          }
      }

      detailList.push(obj);
    },
    delExpenses(detailList, index) {
      detailList.splice(index, 1);
    },
    /** 查询收付款管理列表 */
    getList() {
      this.loading = true;
      this.queryParams = { ...this.queryParams, ...this.query };
      if(this.queryParams.moneyType === '0'){
        this.getCollectionAmtList()
      } else {
        this.getPayAmtList()
      }
    },
    getPayAmtList(){
      getPayAmtList(this.queryParams).then((response) => {
        this.collectPayMoneyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCollectionAmtList(){
      getCollectionAmtList(this.queryParams).then((response) => {
        this.collectPayMoneyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    submit(row) {
      submit(row).then((res) => {
        this.$message.success("提交成功");
        this.getList();
      });
    },
    cancelInfo(row) {
      cancelInfo(row).then((res) => {
        this.$message.success("撤回成功");
        this.getList();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        collectPayMoneyId: null,
        moneyType: "1",
        userId: null,
        orderId: null,
        projectId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        auditStatus: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        delFlag: null,
        collectDetailsList: [
          {
            collectDetailsName: null,
            collectDetailsTime: new Date(),
            collectDetailsAmount: 0,
            collectDetailsStatus: "0",
          },
        ],
        payDetailsList: [
          {
            detailsName: null,
            payDetailsTime: new Date(),
            detailsAmount: 0,
            payDetailsStatus: "0",
            remark: "",
          },
        ],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.collectPayMoneyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收付款管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const collectPayMoneyId = row.collectPayMoneyId || this.ids;
      getCollectPayMoney(collectPayMoneyId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收付款管理";
      });
    },
    /** 提交按钮 */
    submitForm(auditStatus) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.auditStatus = auditStatus;
          if (this.form.collectPayMoneyId != null) {
            updateCollectPayMoney(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCollectPayMoney(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const collectPayMoneyIds = row.collectPayMoneyId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除收付款管理编号为"' + collectPayMoneyIds + '"的数据项？'
        )
        .then(function () {
          return delCollectPayMoney(collectPayMoneyIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/collectPayMoney/export",
        {
          ...this.queryParams,
        },
        `collectPayMoney_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
::v-deep .collectDetailsList .el-table--medium .el-table__cell {
  padding: 0;
}

::v-deep .collectDetailsList .el-input--medium {
  margin: 10px 10px 10px -10px;
}
</style>